package com.codeavatar.hardwaretester.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.codeavatar.catools.helper.CaHardwareHelper;
import com.codeavatar.catools.helper.CaLogHelper;
import com.codeavatar.catools.helper.CaReceiverHelper;
import com.codeavatar.catools.helper.CaToastHelper;
import com.codeavatar.catools.tool.CaConvertTool;
import com.codeavatar.hardwaretester.model.BluetoothCharacteristicModel;
import com.codeavatar.hardwaretester.model.BluetoothConnectModel;
import com.codeavatar.hardwaretester.model.BluetoothDeviceModel;
import com.codeavatar.hardwaretester.model.BluetoothServiceModel;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2022
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 **/
//蓝牙（低功耗蓝牙，传统篮牙）
//传统蓝牙适用于电池使用强度较大的操作,另一个则相反
//低功耗蓝牙(蓝牙4.0+)
@SuppressLint("MissingPermission")
public class BluetoothBleService extends Service {

    private final String TAG = this.getClass().getSimpleName();

    public static final int SID = 0x90001;

    private static BluetoothBleService service;

    //设置广播
    public static final String ACTION_APP_BLE = "codeavatar.action.ble";
    public static final String ACTION_APP_BLE_CHANGE = "codeavatar.action.ble.change";
    public static final String PERMISSION_APP_BLUETOOTH = "com.codeavatar.hardwaretester.APP_BLUETOOTH";

    private boolean isEnabled = false;//服务状态
    private boolean isConnecting = false;//蓝牙状态
    private boolean isDiscovering = false;//搜索状态
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner bluetoothLeScanner;
    private List<BluetoothDeviceModel> bluetoothDeviceModelList;
    private Map<String,ScanResult> scanResultMap;
    private BluetoothConnectModel bluetoothConnectModel;
    private BluetoothGatt bluetoothGatt; //中央服务
    private CaReceiverHelper caReceiverHelper;

    //绑程操作
    private HandlerThread handlerThread;
    private Handler handler;
//    private Timer timer = new Timer();

    //++++++++++++++++++++++++++++++++++++++
    //++ 外部方法
    //++++++++++++++++++++++++++++++++++++++

    public List<BluetoothDeviceModel> getDeviceList(){
        return this.bluetoothDeviceModelList;
    }

    public BluetoothConnectModel getBluetoothConnectModel(){
        return this.bluetoothConnectModel;
    }

    public boolean isEnabled(){
        return this.isEnabled;
    }

    public boolean isConnecting() {
        return isConnecting;
    }

    public boolean isDiscovering() {
        return isDiscovering;
    }

    public static BluetoothBleService init(){
        return service;
    }

    //++++++++++++++++++++++++++++++++++++++
    //++ 内部方法
    //++++++++++++++++++++++++++++++++++++++

    private void asyncScanResult(ScanResult scanResult){
        if(null != scanResultMap && null != scanResult){
            BluetoothDevice device = scanResult.getDevice();
            if(!scanResultMap.containsKey(device.getAddress())){
                scanResultMap.put(device.getAddress(),scanResult);
                BluetoothDeviceModel deviceModel = new BluetoothDeviceModel(scanResult.getDevice().getName(),scanResult.getDevice().getAddress());
                deviceModel.setBluetoothDevice(scanResult.getDevice());
                bluetoothDeviceModelList.add(deviceModel);
                CaLogHelper.warn(TAG,String.format("[bluetoothScanCallBack]搜索到新设备了(%s，%s,%d dB)...",device.getName(),device.getAddress(),scanResult.getRssi()));
                //发现新设备
                sendBroadcastToReceiver("ble_found_device");
            }
        }
    }

    private void initBluetooth(){
        //注册接受者
        this.initRegisterReveiver();
        //初始变量
        bluetoothDeviceModelList = new ArrayList<>();
        bluetoothConnectModel = new BluetoothConnectModel();
        //开启适配器
        //(方式一)
        BluetoothManager blutoothManager=(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = blutoothManager.getAdapter();
//        //(方式二)
//        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(this.isHasAdapter()){
            if(!bluetoothAdapter.isEnabled()){
                bluetoothAdapter.enable();
            }
            bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        }
    }

    private void doDiscovery(){
        if(!this.isHasAdapter()) return;

        if(!CaHardwareHelper.init().isLocationOpen(this)){
            CaToastHelper.toast(this,"请打开定位功能！");
            return;
        }
        bluetoothDeviceModelList.clear();
        Set<BluetoothDevice> boundDevices = bluetoothAdapter.getBondedDevices();
        if(boundDevices.size()>0){
            for (BluetoothDevice device : boundDevices){
                BluetoothDeviceModel deviceModel = new BluetoothDeviceModel(device.getName(),device.getAddress());
                deviceModel.setBluetoothDevice(device);
                bluetoothDeviceModelList.add(deviceModel);
            }
            sendBroadcastToReceiver("ble_found_device");
            CaLogHelper.info(TAG,"【doDiscovery】蓝牙获取绑定的外围设备...");
        }else {
//            if(!bluetoothAdapter.isDiscovering()){
//                bluetoothAdapter.startDiscovery();
//            }
            if(null != bluetoothLeScanner){
                if(null == scanResultMap){
                    scanResultMap = new HashMap<>();
                }else{
                    scanResultMap.clear();
                }
                bluetoothLeScanner.startScan(null,this.getScanSettings(),this.bluetoothScanCallBack);
                isDiscovering = true;
//                //定时通知显示新设备
//                timer.schedule(new TimerTask() {
//                    @Override
//                    public void run() {
//                        sendBroadcastToReceiver("ble_found_device");
//                    }
//                },0,1000);
                CaLogHelper.info(TAG,"【doDiscovery】蓝牙开始搜索外围设备...");
            }
        }
    }

    private ScanSettings getScanSettings() {
        ScanSettings.Builder builder = new ScanSettings.Builder();
        //3种模式：SCAN_MODE_LOW_POWER、SCAN_MODE_BALANCED、SCAN_MODE_LOW_LATENCY
        builder.setScanMode(ScanSettings.SCAN_MODE_BALANCED);
        //芯片组支持批处理芯片上的扫描
//        if (bluetoothAdapter.isOffloadedScanBatchingSupported()) {
//            //设置蓝牙LE扫描的报告延迟的时间（以毫秒为单位）
//            //设置为0以立即通知结果
//            builder.setReportDelay(1000);//设置延迟返回时间(毫秒值) [设置后onBatchScanResults运行]
//        }
        return builder.build();
    }

    private void doUndisconvery(){
        if(null != bluetoothLeScanner){
            bluetoothLeScanner.stopScan(this.bluetoothScanCallBack);
            isDiscovering = false;
            sendBroadcastToReceiver("ble_service_state");
//            timer.cancel(); timer.purge();
            CaLogHelper.warn(TAG,"【doUndisconvery】蓝牙停止搜索...");
        }
    }

    private ScanCallback bluetoothScanCallBack = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();
            handler.post(()->{
                asyncScanResult(result);
            });
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            CaLogHelper.info(TAG,"[bluetoothScanCallBack]共搜索到"+results.size()+"个设备...");

            handler.post(()->{
                bluetoothDeviceModelList.clear();
                for (ScanResult result : results){
                    asyncScanResult(result);
                }
            });
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            CaLogHelper.error(TAG,"[bluetoothScanCallBack]搜索设备失败...");
            isDiscovering = false;
        }
    };

    private void doConnect(){
//        bluetoothAdapter.cancelDiscovery();
        doUndisconvery();
        BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(bluetoothConnectModel.getBluetoothDevice().getAddress());
        bluetoothGatt = bluetoothDevice.connectGatt(this,false,bluetoothGattCallback);

        CaLogHelper.info(TAG,"【doConnect】蓝牙开始连接...");
    }

    private void doDisconnect(){
        if(null != bluetoothGatt){
            bluetoothGatt.disconnect();
            bluetoothGatt.close();
            CaLogHelper.warn(TAG,"【doDisconnect】蓝牙断开连接...");
        }
    }

    /**
     * 蓝牙返回数据函数
     * 方法体在service中,不得在方法体中使用更新界面的操作以及Toast,否则程序无法运行!!!
     */
    private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            CaLogHelper.info(TAG, "【BluetoothGattCallback】onConnectionStateChange");
            CaLogHelper.info(TAG, String.format("status=%d》newState=%d",status,newState));
            if(status == BluetoothGatt.GATT_SUCCESS){
                if (newState == BluetoothProfile.STATE_CONNECTED) {//连接成功
                    CaLogHelper.info(TAG, "【BluetoothGattCallback】蓝牙设备已连接成功...");
                    isConnecting = true;
                    //搜索设备服务集合Service
                    bluetoothGatt.discoverServices();
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//断开连接
                    CaLogHelper.error(TAG, "【BluetoothGattCallback】蓝牙设备已断开连接...");
                    isConnecting = false;
                    doDisconnect();// 防止出现status 133
                }else{
                    //失败处理
                    CaLogHelper.error(TAG, "【BluetoothGattCallback】蓝牙设备连接失败...");
                    isConnecting = false;
                }
            }else{
                isConnecting = false;
                doDisconnect();// 防止出现status 133
                doConnect();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            CaLogHelper.info(TAG, "【BluetoothGattCallback】onServicesDiscovered");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                CaLogHelper.info(TAG, "【BluetoothGattCallback】蓝牙设备已搜索到服务...");
                //组装服务
                List<BluetoothGattService> services = gatt.getServices();
                List<BluetoothServiceModel> tmpServiceModelList = new ArrayList<>();
                for(BluetoothGattService service:services){
                    BluetoothServiceModel serviceModel = new BluetoothServiceModel();
                    serviceModel.setBluetoothGattService(service);
                    serviceModel.setUuid(service.getUuid().toString());
                    //组装特征
                    List<BluetoothCharacteristicModel> tmpCharacteristicModelList = new ArrayList<>();
                    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                    for (BluetoothGattCharacteristic characteristic : characteristics){
                        BluetoothCharacteristicModel characteristicModel = new BluetoothCharacteristicModel();
                        characteristicModel.setBluetoothGattCharacteristic(characteristic);
                        characteristicModel.setUuid(characteristic.getUuid().toString());
                        //组装描述符
                        characteristicModel.setBluetoothGattDescriptorList(characteristic.getDescriptors());
                        tmpCharacteristicModelList.add(characteristicModel);

//                        if(null != bluetoothConnectModel.getBluetoothGattCharacteristic()){
//                            if (characteristic.getUuid().toString().equals(bluetoothConnectModel.getBluetoothGattCharacteristic().getUuid().toString())) {
//                                // 订阅信息,否则接收不到数据
//                                onCharacteristicNotification(characteristic, true);
//                            }
//                        }
                    }
                    serviceModel.setCharacteristicModelList(tmpCharacteristicModelList);
                    tmpServiceModelList.add(serviceModel);
                }
                //放入对应的设备中
                bluetoothDeviceModelList.get(bluetoothConnectModel.getBluetoothDeviceIndex()).setServiceModelList(tmpServiceModelList);
                //发现服务
                sendBroadcastToReceiver("ble_found_service");
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            CaLogHelper.info(TAG, "【BluetoothGattCallback】onCharacteristicRead");
//            super.onCharacteristicRead(gatt, characteristic, status);
            CaLogHelper.info(TAG,
                    String.format("向设备[%s]的特征[%s]读取数据，响应状态码[%d]...",gatt.getDevice().getAddress(),characteristic.getUuid().toString(),status));
            if (status == BluetoothGatt.GATT_SUCCESS) {
                CaLogHelper.info(TAG, "【BluetoothGattCallback】读取数据成功...");
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            CaLogHelper.info(TAG, "【BluetoothGattCallback】onCharacteristicWrite");
//            super.onCharacteristicWrite(gatt, characteristic, status);
            CaLogHelper.info(TAG,
                    String.format("向设备[%s]的特征[%s]写入数据，响应状态码[%d]...",gatt.getDevice().getAddress(),characteristic.getUuid().toString(),status));
            if (status == BluetoothGatt.GATT_SUCCESS) {
                CaLogHelper.info(TAG, "【BluetoothGattCallback】写入数据成功...");
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            CaLogHelper.info(TAG, "【BluetoothGattCallback】onCharacteristicChanged");
//            super.onCharacteristicChanged(gatt, characteristic);
            String characteristicVal = CaConvertTool.bytes2HexString(characteristic.getValue());
            CaLogHelper.info(TAG,
                    String.format("监测设备[%s]的特征[%s]的响应数据，特征值：[%s]...",
                            gatt.getDevice().getAddress(),characteristic.getUuid().toString(),characteristicVal));

            Bundle extras = new Bundle();
            extras.putString("action","ble_response");
            extras.putString("value",characteristicVal);
            sendBroadcastToReceiver(extras);
        }

    };
    //监听通知
    private boolean onCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled){
        if(null == this.bluetoothGatt) return false;
        CaLogHelper.info(TAG, "【onCharacteristicNotification】蓝牙开启服务特征值通知监听...");
        BluetoothGattDescriptor descriptor = characteristic.getDescriptors().get(0);
        if(null != descriptor){
            descriptor.setValue(enabled?BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE:BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
            bluetoothGatt.writeDescriptor(descriptor);
        }
        return bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    }
    //监听指示
    private boolean onCharacteristicIndication(BluetoothGattCharacteristic characteristic){
        if(null == this.bluetoothGatt) return false;
        CaLogHelper.info(TAG, "【onCharacteristicIndication】蓝牙开启服务特征值指示监听...");
        BluetoothGattDescriptor descriptor = characteristic.getDescriptors().get(0);
        if(null != descriptor){
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
            bluetoothGatt.writeDescriptor(descriptor);
        }
        return bluetoothGatt.setCharacteristicNotification(characteristic, true);
    }
    //写入数据
    private boolean doSendData(byte[] data,boolean isRead){
        if(null != this.bluetoothGatt){
            BluetoothGattCharacteristic characteristic = bluetoothConnectModel.getBluetoothGattCharacteristic();
            //最大20byte
            characteristic.setValue(data);
            boolean writeResult = this.bluetoothGatt.writeCharacteristic(characteristic);
            CaLogHelper.info(TAG,
                    String.format("【doSendData】向设备[%s]的服务[%s]特征[%s]写入[%s]%s...",
                    bluetoothConnectModel.getBluetoothDevice().getAddress(),
                    bluetoothConnectModel.getBluetoothGattService().getUuid().toString(),
                    characteristic.getUuid().toString(),
                    CaConvertTool.bytes2HexString(data),
                    (writeResult?"成功":"失败"))
            );
            if(isRead){ doReadData(); }
            return writeResult;
        }
        return false;
    }
    //读取数据
    private boolean doReadData(){
        if(null != this.bluetoothGatt){
            CaLogHelper.info(TAG, "【doReadData】蓝牙读取服务特征值...");
            BluetoothGattCharacteristic characteristic = bluetoothConnectModel.getBluetoothGattCharacteristic();
            boolean readResult = this.bluetoothGatt.readCharacteristic(characteristic);
            CaLogHelper.info(TAG,
                    String.format("【doReadData】向设备[%s]的服务[%s]特征[%s]读取数据%s...",
                            bluetoothConnectModel.getBluetoothDevice().getAddress(),
                            bluetoothConnectModel.getBluetoothGattService().getUuid().toString(),
                            characteristic.getUuid().toString(),
                            (readResult?"成功":"失败"))
            );
            return readResult;
        }
        return  false;
    }

    private void initRegisterReveiver(){
        IntentFilter connectStateChangeFilter = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        IntentFilter stateChangedFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        IntentFilter aclConnectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        IntentFilter aclDisconnectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothDeviceReceiver,connectStateChangeFilter);
        registerReceiver(bluetoothDeviceReceiver,stateChangedFilter);
        registerReceiver(bluetoothDeviceReceiver,aclConnectedFilter);
        registerReceiver(bluetoothDeviceReceiver,aclDisconnectedFilter);
        //注册发现设备接受者
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(bluetoothDeviceReceiver,foundFilter);
    }

    private void uninitRegisterReveiver(){
        unregisterReceiver(bluetoothDeviceReceiver);
        caReceiverHelper.unregisterReceiver();
    }

    private BroadcastReceiver bluetoothDeviceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            CaLogHelper.info(TAG,"[bluetoothDeviceReceiver]蓝牙接受者的Action（"+action+"）...");
            if(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)){

            }else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                sendBroadcastToReceiver("ble_state_change");
            }else if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){

            }else if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){

            }else if(BluetoothDevice.ACTION_FOUND.equals(action)){
//                // 从 Intent 中获取发现的 BluetoothDevice
//                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                BluetoothDeviceModel deviceModel = new BluetoothDeviceModel(device.getName(),device.getAddress());
//                deviceModel.setBluetoothDevice(device);
//                bluetoothDeviceModelList.add(deviceModel);
//                sendBroadcastToReceiver("ble_found_device");
            }
        }
    };

    private void sendBroadcastToReceiver(Bundle extras){
        if(null == extras) extras = new Bundle();
        caReceiverHelper.sendBroadcast(ACTION_APP_BLE_CHANGE, PERMISSION_APP_BLUETOOTH,extras);
    }
    private void sendBroadcastToReceiver(String action){
        Bundle extras = new Bundle();
        extras.putString("action",action);
        sendBroadcastToReceiver(extras);
    }

    private boolean isHasAdapter(){
        return (null != bluetoothAdapter);
    }

    private void stopService(){
        this.stopSelf();
    }

    private void initData(){
        //设置当前对象
        service = this;
        //注意订阅者
        caReceiverHelper = new CaReceiverHelper(getApplication(),broadcastReceiver);
        caReceiverHelper.registerReceiver(ACTION_APP_BLE, PERMISSION_APP_BLUETOOTH);
        //服务状态
        this.isEnabled = true;//服务开始运行
        sendBroadcastToReceiver("ble_service_state");
        //线程初始化
        handlerThread = new HandlerThread(TAG+"-handler");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());
    }

    private void uninitData(){
        service = null;
        this.isEnabled = false;//服务状态
        sendBroadcastToReceiver("ble_service_state");
        //线程
        if(null != handlerThread){
            handlerThread.quit();
        }
        //销毁变量
        bluetoothGatt = null;
        bluetoothAdapter = null;
    }

    //信息通道
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CaLogHelper.info(TAG,"[broadcastReceiver]蓝牙服务接收到来自的外部消息。。。。。。");
            Bundle extras = intent.getExtras();
            if(null != extras){
                CaLogHelper.info(extras);
                String action = extras.getString("action");
                if("ble_discovery".equals(action)){
                    doDiscovery();
                }else if("ble_undiscovery".equals(action)){
                    doUndisconvery();
                }else if("ble_connect".equals(action)){
                   String type = extras.getString("type");
                   int position = extras.getInt("position");
                   if("device".equals(type)){
                       bluetoothConnectModel.setBluetoothDevice(bluetoothDeviceModelList.get(position).getBluetoothDevice());
                       bluetoothConnectModel.setBluetoothDeviceIndex(position);
                       doConnect();
                   }else if("service".equals(type)){
                       List<BluetoothServiceModel> list = bluetoothDeviceModelList.get(bluetoothConnectModel.getBluetoothDeviceIndex()).getServiceModelList();
                       bluetoothConnectModel.setBluetoothGattService(list.get(position).getBluetoothGattService());
                       bluetoothConnectModel.setBluetoothGattServiceIndex(position);
                       //发现服务
                       sendBroadcastToReceiver("ble_found_characteristic");
                   }else if("character".equals(type)){
                       List<BluetoothServiceModel> slist = bluetoothDeviceModelList.get(bluetoothConnectModel.getBluetoothDeviceIndex()).getServiceModelList();
                       List<BluetoothCharacteristicModel> clist = slist.get(bluetoothConnectModel.getBluetoothGattServiceIndex()).getCharacteristicModelList();
                       bluetoothConnectModel.setBluetoothGattCharacteristic(clist.get(position).getBluetoothGattCharacteristic());
                       bluetoothConnectModel.setBluetoothGattCharacteristicIndex(position);
                       //发现服务
                       sendBroadcastToReceiver("ble_found_finish");
                       onCharacteristicNotification(bluetoothConnectModel.getBluetoothGattCharacteristic(),true);
                   }
                }else if("ble_send".equals(action)) {
                    String cmd = extras.getString("cmd");
                    doSendData(CaConvertTool.hexString2Bytes(cmd),true);
                }else{
                    CaLogHelper.warn(TAG,"未匹配到["+action+"]的操作...");
                }
            }
        }
    };

    //++++++++++++++++++++++++++++++++++++++
    //++ 重写方法
    //++++++++++++++++++++++++++++++++++++++

    @Override
    public void onCreate() {
        CaLogHelper.info(TAG,"onCreate");
        super.onCreate();
        this.initData();
        this.initBluetooth();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        CaLogHelper.info(TAG,"onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        CaLogHelper.info(TAG,"onBind");
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
        CaLogHelper.info(TAG,"onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        CaLogHelper.info(TAG,"onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        CaLogHelper.info(TAG,"onDestroy");
        //停止搜索
        doUndisconvery();
        doDisconnect();
        //注销接受者
        uninitRegisterReveiver();
        uninitData();
        super.onDestroy();
    }
}
